﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;

namespace MediaCenterExractor
{
    class SubtitlesHandler
    {
        private const string SearchBase = "http://www.subscenter.org/he/subtitle/search/?q={0}";
        private const string DownloadBase = "http://www.subscenter.org/he";

        public static bool LoadSubtitles(string title, string finalPath)
        {
            try
            {
                var webClient = new WebClient();

                Uri uri = new Uri(string.Format(SearchBase, title));

                Logger.Write("Looking for subtitles..");
                var browserForm = new Browser(uri);

                Application.Run(browserForm);

                var html = browserForm.Html;

                var htmlDocument = Html.Utilities.HtmlHelper.CreateDocument(html);
                string downloadPath = GetDownloadPath(htmlDocument, title);

                if (string.IsNullOrEmpty(downloadPath))
                {
                    return false;
                }

                Logger.Write("Subtitles found, downloading..");

                if (!Directory.Exists(finalPath))
                    Directory.CreateDirectory(finalPath);

                Uri downloadUri = new Uri(DownloadBase + downloadPath);

                var subtitlesFileName = Path.Combine(finalPath, title + "-subs.zip");
                webClient.DownloadFile(downloadUri, subtitlesFileName);

                Logger.Write(string.Format("Subtitles downloaded to:{0}, exracting..", subtitlesFileName));

                var process = Process.Start("winrar", string.Format("e -o+ -ibck -y \"{0}\" \"{1}\"", subtitlesFileName, finalPath));
                if (process != null)
                {
                    process.WaitForExit();
                    File.Delete(subtitlesFileName);
                }

                return true;
            }
            catch (Exception ex)
            {
                Logger.Write(string.Format("Error looking for subtitles \r\n {0}", ex));
                return false;
            }
        }

        private static string GetDownloadPath(HtmlDocument htmlDocument, string title)
        {
            // Simple case
            var downloadBtns = htmlDocument.DocumentNode.SelectNodes("//*[@class=\"subsDownloadBtn\"]");
            var titleLower = title.ToLower();
            if (downloadBtns != null)
            {
                foreach (var downloadBtn in downloadBtns)
                {
                    var url = downloadBtn.FirstChild.Attributes["onclick"];
                    if (url.Value.ToLower().Contains(titleLower))
                    {
                        // example: return download_adv_boxy('/subtitle/download/he/261008/?v=Suits.S02E11.HDTV.x264-ASAP&key=9056006b668e23ed7450917a62439b72');
                        var match = Regex.Match(url.Value, "return download_adv_boxy\\('([^']*)'\\);");
                        return match.Groups[1].Value;
                    }
                }
            }

            // select list case
            // example: /subtitle/download/he/65371/?v=Reservoir.Dogs.1992.1080p.BluRay.x264-WPi&key=d181ef614a27036fa4f35d02540ae72f
            var versionLists = htmlDocument.DocumentNode.SelectNodes("//*[@class=\"selectSubsVersion\"]");
            if (versionLists != null)
            {
                foreach (var versionList in versionLists)
                {
                    foreach (var option in versionList.FirstChild.Elements("option"))
                    {
                        if (option.NextSibling !=null && option.NextSibling.InnerText.ToLower().Contains(titleLower))
                        {
                            var parts = option.Attributes["value"].Value.Split('/');
                            return string.Format("/subtitle/download/he/{0}/?v={1}&key={2}", parts[0], title, parts[1]);
                        }
                    }
                }
            }
            return null;
        }
    }
}
